﻿using System.Reflection;

namespace PropertyManagementWebApi.Extensions
{
    public static class ServiceRegistrationExtensions
    {
        public static IServiceCollection RegisterServicesByConvention(this IServiceCollection services, Assembly assembly, Type baseType, ServiceLifetime lifetime = ServiceLifetime.Scoped)
        {
            var types = assembly.GetTypes()
                .Where(t => baseType.IsAssignableFrom(t) && !t.IsAbstract && !t.IsInterface);

            foreach (var type in types)
            {
                var interfaces = type.GetInterfaces();
                if (interfaces.Length > 0)
                {
                    foreach (var @interface in interfaces)
                    {
                        services.Add(new ServiceDescriptor(@interface, type, lifetime));
                    }
                }
                else
                {
                    services.Add(new ServiceDescriptor(type, type, lifetime));
                }
            }

            return services;
        }
    }
}
